package interceptor;

import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.config.entities.ResultConfig;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class ConfigInterceptor implements Interceptor {

	private static final long serialVersionUID = 9094505428375700475L;

	private static final Boolean MODE = false;
	private static final Boolean SHOWSESSION = false;

	public void init() {
		System.out.println("运行状态拦截器初始化");
	}

	public void destroy() {
	}

	public String intercept(ActionInvocation actionInvocation) throws Exception {

		if (MODE) {
			String originalAccessUrl = ServletActionContext.getRequest().getRequestURL().toString();
			String accessMethod = ServletActionContext.getRequest().getMethod();
			String parameters = "";
			String debugUrl = "";

			if ("get".equalsIgnoreCase(accessMethod)) {
				parameters = ServletActionContext.getRequest().getQueryString();
				debugUrl = originalAccessUrl + ((parameters == null) || ("".equals(parameters.trim())) ? "" : new StringBuilder("?").append(parameters).toString());
			} else {
				parameters = getParameters(ServletActionContext.getRequest());
				debugUrl = originalAccessUrl + ((parameters == null) || ("".equals(parameters.trim())) ? "" : new StringBuilder("?").append(parameters).toString());
			}

			long startTime = System.currentTimeMillis();
			long executionTime = System.currentTimeMillis() - startTime;

			int i = 1;
			System.out.println(i++ + "." + "accessMethod" + "：" + accessMethod);
			System.out.println(i++ + "." + "debugUrl" + "：" + debugUrl);
			if ((parameters != null) && (!"".equals(parameters.trim()))) {
				System.err.println(i++ + "." + "parameters(Multirow)" + "：" + "\n" + "  " + parameters.replaceAll("&", new StringBuilder("\n").toString()));
			}
			System.out.println(i++ + "." + "actionAndMethod" + ":" + actionInvocation.getProxy().getAction().getClass().getName() + "." + actionInvocation.getProxy().getMethod() + "()");
			System.out.println(i++ + "." + "executeTime" + ":" + executionTime + "ms");

			Map<String, ResultConfig> results = actionInvocation.getProxy().getConfig().getResults();
			ResultConfig resultConfig = null;
			resultConfig = (ResultConfig) results.get(actionInvocation.invoke());
			if (resultConfig != null) {
				if (resultConfig.getLocation() != null) {
					System.out.println(i++ + "." + "configFilePath" + ":" + resultConfig.getLocation().getURI());
					System.out.println(i++ + "." + "configFileLineNumber" + ":" + resultConfig.getLocation().getLineNumber());
				}
				System.out.println(i++ + "." + "actionReturnResult" + ":" + resultConfig.getName());
				System.out.println(i++ + "." + "actionReturnView" + ":" + resultConfig.getParams());
			} else {
				System.out.println(i++ + ".there is no result config ");
			}

			if (SHOWSESSION) {
				System.out.println(i++ + "." + "session" + ":");
				Map<String, Object> httpSession = actionInvocation.getInvocationContext().getSession();
				for (Iterator<String> iterator = httpSession.keySet().iterator(); iterator.hasNext();) {
					String key = (String) iterator.next();
					System.out.println("  " + key + "=" + httpSession.get(key));
				}
			}

			System.out.println();

		}
		return actionInvocation.invoke();

	}

	private String getParameters(ServletRequest request) {
		Enumeration<?> paramNames = request.getParameterNames();
		StringBuffer params = new StringBuffer();
		while ((paramNames != null) && (paramNames.hasMoreElements())) {
			String paramName = (String) paramNames.nextElement();
			String[] values = request.getParameterValues(paramName);
			if ((values != null) && (values.length != 0)) {
				if (values.length == 1)
					params.append(paramName + "=" + values[0] + "&");
				else {
					for (int i = 0; i < values.length; i++)
						params.append(paramName + "=" + values[i] + "&");
				}
			}
		}
		if (params.length() > 0) {
			return params.substring(0, params.length() - 1);
		}
		return params.toString();
	}

}
